# -*- coding: utf-8 -*-
"""
# @created on : 9月 2021/9/16 09:52
# @author     : kevin
# @file       : multipart.py
# @software   : PyCharm
# @project    : auto_interface_test


@license: (C) Copyright 2019-2025, Corporation Limited.
@desc:
"""
import ast
from basic_method.variable import OperationVariable
import random
import string
from common.logger import Logger


class Multipart:
    def __init__(self):
        self.mutipart_data = {'data': '', 'headers': ''}
        self.boundart = None

    def creat_boundary(self, simp_len, simp='----WebKitFormBoundary'):
        self.boundart = simp + ''.join(random.sample(string.ascii_letters + string.digits, simp_len - len(simp)))
        return self.boundart

    def to_form_data(self, data, simp_len, headers, simp='----WebKitFormBoundary'):
        self.mutipart_data['headers'] = headers
        boundary = self.creat_boundary(int(simp_len), simp)
        jion_str = '--{}\r\nContent-Disposition: form-data; name="{}"\r\n\r\n{}\r\n'
        end_str = "--{}--".format(boundary)
        args_str = ""
        # 判断data类型如果不是dict，则将data转为dict类型
        if not isinstance(data, dict):
            data = ast.literal_eval(data)
        for key, value in data.items():
            args_str = args_str + jion_str.format(boundary, key, value)

        args_str = args_str + end_str.format(boundary)
        args_str = args_str.replace("\'", "\"").replace('False', 'false').replace('True', 'true')
        self.mutipart_data['data'] = args_str
        self.mutipart_data['headers']['Accept'] = 'application/json, text/javascript, */*; q=0.01'
        self.mutipart_data['headers']['X-Requested-With'] = 'XMLHttpRequest'
        self.mutipart_data['headers']['Content-Type'] = 'multipart/form-data; boundary=' + self.boundart
        return self.mutipart_data


class UpdataData():
    def __init__(self):
        self.log = Logger()
        self.qu = OperationVariable()

    """
    取变量值更新data里对应的值
    """
    def up_data(self, need, data):
        data = ast.literal_eval(data)
        c = need.split(';')
        try:
            for i in range(0, len(c)):
                key = c[i]
                value = self.qu.get_value_from_key_value(key)
                data[key] = value
        except UnicodeEncodeError as e:
            self.log.logger('error', f'将变量更新至请求数据时出错， 错误信息为：{e}')
        finally:
            return data